package cn.iocoder.yudao.module.dr.service.collectionmanagement;

import cn.iocoder.yudao.module.dr.controller.admin.collectionlinkaddress.vo.CollectionLinkAddressSaveReqVO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionlinkaddress.CollectionLinkAddressDO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionmanagement.CollectionManagementDO;
import cn.iocoder.yudao.module.dr.dal.mysql.collectionlinkaddress.CollectionLinkAddressMapper;
import cn.iocoder.yudao.module.dr.service.collectionlinkaddress.CollectionLinkAddressService;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.api.file.dto.FileCreateReqDTO;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class CollectionAttachmentImportServiceImpl implements CollectionAttachmentImportService {

    @Resource
    private CollectionManagementService collectionManagementService;
    
    @Resource
    private CollectionLinkAddressService collectionLinkAddressService;

    @Resource
    CollectionLinkAddressMapper collectionLinkAddressMapper;
    
    @Resource
    private FileApi fileApi; // Yudao文件上传接口

    @Override
    public void initAttach(){
        try {
            Map<String, String> map = new HashMap<>();
            map.put("二维成果提交", "1");
            map.keySet().forEach(key -> {
                log.info("异步初始化附件：{}", key);
                importAttachmentsFromDirectory("F:\\" + key,map.get(key));
            });
        } catch (Exception e) {
            log.error("异步初始化失败", e);
        }

        log.info("初始化完成：{}");
    }

    /**
     * 导入指定目录下的所有附件
     * @param baseDir 基础目录路径
     */
    @Override
    public void importAttachmentsFromDirectory(String baseDir,String type) {
        File rootDir = new File(baseDir);
        if (!rootDir.exists() || !rootDir.isDirectory()) {
            throw new RuntimeException("目录不存在或不是有效目录: " + baseDir);
        }

        // 遍历一级子目录
        for (File collectionDir : rootDir.listFiles(File::isDirectory)) {
            try {
                processCollectionDirectory(collectionDir,type);
            } catch (Exception e) {
                log.error("处理藏品目录失败: {}", collectionDir.getName(), e);
            }
        }
    }

    /**
     * 处理单个藏品目录
     */
    private void processCollectionDirectory(File collectionDir,String type) {
        log.info("处理藏品目录: {}", collectionDir.getName());
        // 解析目录名获取藏品编号
        String dirName = collectionDir.getName();
        Matcher matcher = Pattern.compile("^(\\d+)").matcher(dirName);
        if (!matcher.find()) {
            log.warn("跳过无效目录名格式: {}", dirName);
            return;
        }

        String generalAccessionNumber = matcher.group(1);
        // 验证藏品是否存在
        CollectionManagementDO collection = collectionManagementService.selectByGeneralAccessionNumber(generalAccessionNumber);
        if (collection == null) {
            log.warn("藏品ID不存在: {}", generalAccessionNumber);
            return;
        }

        // 递归处理所有文件
        processFilesInDirectory(collectionDir,collection.getId(), generalAccessionNumber,type);
    }

    /**
     * 递归处理目录中的所有文件
     */
    private void processFilesInDirectory(File dir,Long collectionId, String generalAccessionNumber,String type) {
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                // 递归处理子目录
                processFilesInDirectory(file,collectionId, generalAccessionNumber,type);
            } else if (file.isFile()) {
                try {
                    log.info("藏品：{}查到到附件：{}",generalAccessionNumber,file.getAbsolutePath());
                    uploadAndLinkFile(file, collectionId,generalAccessionNumber,type);
                    log.info("藏品：{}查到到附件：{} 处理完成",generalAccessionNumber,file.getAbsolutePath());
                } catch (Exception e) {
                    log.error("文件处理失败: {}", file.getAbsolutePath(), e);
                }
            }
        }
    }

    /**
     * 上传文件并关联到藏品
     */
    private void uploadAndLinkFile(File file, Long collectionId,String generalAccessionNumber,String type) throws IOException {
        // 检查文件大小（例如限制为100MB）
        long maxFileSize = 1000 * 1024 * 1024; // 100MB
        if (file.length() > maxFileSize) {
            log.warn("文件过大，跳过处理: {} (大小: {} bytes)", file.getAbsolutePath(), file.length());
            return;
        }


        // 判断文件类型：如果是图片则使用原type，否则设置为6
        String finalType = type;
        String fileName = file.getName().toLowerCase();
        if (!isImageFile(fileName)) {
            finalType = "6"; // 非图片文件类型设置为6
            log.info("文件{}被识别为非图片，类型设置为: {}", file.getName(), finalType);
        }else{
            if(file.getPath().contains("展示浏览图")){
                log.info("初始化主图：");
                LambdaQueryWrapper<CollectionLinkAddressDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(CollectionLinkAddressDO::getCollectionId, collectionId);
                queryWrapper.eq(CollectionLinkAddressDO::getType, 0);
                Boolean exit = collectionLinkAddressMapper.selectCount(queryWrapper)>0;
                if (!exit) {
                    uploadData(file,generalAccessionNumber,collectionId,"0");
                }
            }
            return;
        }

        // 检查文件是否已存在
        LambdaQueryWrapper<CollectionLinkAddressDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CollectionLinkAddressDO::getCollectionId, collectionId);
        queryWrapper.eq(CollectionLinkAddressDO::getFileName, file.getName());
        CollectionLinkAddressDO daa = collectionLinkAddressMapper.selectOne(queryWrapper);
        if(Objects.nonNull(daa)){
            log.warn("藏品{}文件已存在，跳过上传: {}",generalAccessionNumber ,file.getName());
            return;
        }

        uploadData(file,generalAccessionNumber,collectionId,finalType);
    }

    private void uploadData(File file,String generalAccessionNumber,Long collectionId,String type) throws IOException {
        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }

            // 上传文件到文件服务
            FileCreateReqDTO fileCreateReqDTO = new FileCreateReqDTO();
            fileCreateReqDTO.setPath(file.getName());
            fileCreateReqDTO.setContent(buffer.toByteArray());
            log.info("藏品{}上传附件: {}",generalAccessionNumber ,file.getName());
            String fileUrl = fileApi.createFile(fileCreateReqDTO).getCheckedData();
            log.info("藏品{}上传附件完成: {}",generalAccessionNumber ,file.getName());

            // 创建附件关联记录
            CollectionLinkAddressSaveReqVO createReqVO = new CollectionLinkAddressSaveReqVO();
            createReqVO.setCollectionId(collectionId);
            createReqVO.setFileName(file.getName());
            createReqVO.setLinkAddress(fileUrl);
            createReqVO.setType(type); // 使用最终确定的类型

            collectionLinkAddressService.createCollectionLinkAddress(createReqVO);
        } catch (IOException e) {
            log.error("文件处理失败: {}", file.getAbsolutePath(), e);
            throw e;
        }
    }

    /**
     * 判断文件是否为图片类型
     */
    private boolean isImageFile(String fileName) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tiff", ".tif"};
        for (String ext : imageExtensions) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
    /**
     * 根据文件扩展名确定文件类型
     */
    private String determineFileType(File file) {
        String fileName = file.getName().toLowerCase();
        if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".jpeg") || fileName.endsWith(".CR2")) {
            return "1";
        } else if (fileName.endsWith(".pdf")) {
            return "2";
        } else if (fileName.endsWith(".mp4") || fileName.endsWith(".mov")) {
            return "3";
        }
        return "6";
    }
}
